package tasklist

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"text/template"
)

func TaskStatus(flag int) string {
	if flag == 0 {
		return "未完成"
	} else if flag == 1 {
		return "已完成"
	}
	return "未知状态"
}

func (this *TaskList) Save2Xls(templatefile, savefile string) error {
	funcMap := template.FuncMap{
		"taskStatus": TaskStatus,
	}
	tasks := this.OutputArray()
	saveFD, err := os.Create(savefile)
	if err != nil {
		return err
	}

	t := template.Must(template.New(templatefile).Funcs(funcMap).ParseFiles(templatefile))
	err = t.Execute(saveFD, tasks)
	if err != nil {
		return err
	}
	return nil
}

func (this *TaskList) SaveJson() []byte {
	tasks := this.OutputArray()
	output, err := json.Marshal(tasks)
	if err != nil {
		return nil
	} else {
		return output
	}
}

func (this *TaskList) SaveJsonFile(file string) {
	content := this.SaveJson()
	ioutil.WriteFile(file, content, 0666)
}

func (this *TaskList) ParseTaskJson(file string) *[]*Task {
	tasks := make([]*Task, 0)
	content, err := ioutil.ReadFile(file)
	if err != nil {
		log.Println(err)
		return nil
	}
	err = json.Unmarshal(content, &tasks)
	log.Println(err)
	return &tasks
}

func (this *TaskList) ImportTasksFromJson(file string) {
	tasks := this.ParseTaskJson(file)
	if tasks != nil {
		this.InsertTasks(tasks)
	}
}
